Using attr() with Pseudo-Elements in CSS
The CSS attr() function allows pseudo-elements like ::before and ::after to display the value of an HTML attribute dynamically. This enables you to generate content based on the element's attributes without modifying the HTML.
Use content: attr(attribute-name); to insert the value of a specific attribute.
Only string-based attributes can be displayed using attr(). Numeric or URL values can also be used with certain properties like content.
The attr() function can be combined with other text or symbols in the content property, e.g., content: 'Note: ' attr(data-note);.
This method is ideal for tooltips, labels, counters, or displaying metadata dynamically.
In this example, the ::after pseudo-element reads the data-source attribute of the paragraph and displays it in parentheses after the text. You can change the attribute in HTML, and the pseudo-element will automatically reflect the new value.
Use attr() for dynamically generated text content without extra markup.
Combine with CSS styling like color, font-weight, or text-transform for visual emphasis.
Avoid using pseudo-elements with attr() for interactive or functional content that requires JavaScript events.
Test across browsers; basic attr() support for content is widely supported, but other properties may have limited compatibility.
How would you use attr() and a pseudo-element to display a tooltip text from a data-tooltip attribute on hover?
What happens if you try to use attr(data-count) to show a number inside a ::before pseudo-element on a button — will it render correctly?
A tooltip built with attr() and ::after is showing up blank in production — the HTML has the attribute, but the CSS isn't rendering it. What would you check first?
You're building a reusable card component that uses attr() to inject a category label via ::before. The design team wants to support multi-language labels. Is attr() a good solution here? Why or why not?
You're designing a high-performance accessibility layer that uses attr() to inject ARIA labels via pseudo-elements. What are the performance and SEO implications of relying on CSS for dynamic content instead of the DOM?
A legacy component uses attr() to render dynamic pricing in ::after, but now we need to support real-time price updates. How would you evaluate whether to keep this pattern or refactor to JS?
We're migrating a large UI library from inline JS-generated tooltips to a CSS-only solution using attr(). What architectural risks does this introduce for internationalization, accessibility compliance, and component reusability across teams?
How would you design a system-wide policy around using attr() in pseudo-elements to avoid technical debt, especially when teams might use it as a shortcut instead of proper semantic HTML?